package com.org.cys.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

/**
 * String工具类
 * @author caiyushen
 * */
public class StringUtil extends StringUtils {
    public StringUtil() {
    }

    /**
     * 字符串首字母大写
     * @param str
     * */
    public static String toUpperCaseFirst(String str) {
        if(str != null && !"".equals(str.trim())) {
            String firstChar = str.substring(0, 1).toUpperCase();
            String lastStr = str.substring(1);
            return firstChar + lastStr;
        } else {
            return "";
        }
    }

    /**
     * 字符串首字母小写
     * @param str
     * */
    public static String toLowerCaseFirst(String s) {
        return Character.isLowerCase(s.charAt(0))?s:Character.toLowerCase(s.charAt(0)) + s.substring(1);
    }

    /**
     * 判断字符串不为空
     * */
    public static boolean checkStr(String str) {
        return isNotBlank(str);
    }

    /**
     * 判断对象不为空
     * @param obj
     * */
    public static boolean checkObj(Object obj) {
        boolean bool = true;
        if(obj == null || "".equals(obj.toString().trim())) {
            bool = false;
        }

        return bool;
    }

    /**
     * 对象转数值 String s = "20"; toInteger(s); // 20; Man man = new Man(); man.toString(); // "15" toInteger(man); // 15
     * @param obj
     * */
    public static Integer toInteger(Object obj) {
        return Integer.valueOf(obj != null?Integer.parseInt(obj.toString()):0);
    }

    /**
     * 字符串转数值，如果字符串为空，则返回-1； String s = ""; toInt(s); // -1
     * @param str
     * */
    public static int toInt(String str) {
        return "".equals(str)?-1:Integer.parseInt(str);
    }
    
    
    /**
     * 返回对象不为空的toString方法
     * @param obj
     * */
    public static String toString(Object obj) {
        return obj != null?obj.toString().trim():"";
    }

    /**
     * 字符串编码从ISO8859_1转成GBK
     * @param str
     * */
    public static String getISOToGBK(String str) {
        String strName = "";

        try {
            if(str != null) {
                strName = new String(str.getBytes("ISO8859_1"), "GBK");
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strName;
    }

    
    /**
     * 字符串编码从ISO8859_1转成UTF8
     * @param str
     * */
    public static String getISOToUTF8(String str) {
        String strName = "";

        try {
            if(str != null) {
                strName = new String(str.getBytes("ISO8859_1"), "UTF8");
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strName;
    }

    /**
     * 按给定格式解析字符串为时间对象
     * @param strDate - 日期格式String
	 * @param pattern 时间格式 -SimpleDateFormat
     * */
    public static Date parses(String strDate, String pattern) throws ParseException {
        return (new SimpleDateFormat(pattern)).parse(strDate);
    }

    /**
     * 根据参数获取随机值的整位数
     * @param num
     * */
    public static String getRandom(int num) {
        return (Math.random() + "").substring(2, num + 2);
    }

    /**
     * 判断字符串是否中文
     * @param str
     * */
    public static boolean isChinese(String str) {
        String regEx = "[\\u4e00-\\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 字符串编码UTF-8转换GBK
     * @pram str
     * */
    public static String getStrToGbk(String str) {
        String strName = "";

        try {
            if(str != null) {
                strName = new String(str.getBytes("UTF-8"), "GBK");
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return strName;
    }

    
    /**
     * 字符串首字母大写
     * @param str
     * */
    public static String toFirstUpperCase(String str) {
        if(str != null && !"".equals(str.trim())) {
            String firstChar = str.substring(0, 1).toUpperCase();
            String lastStr = str.substring(1);
            return firstChar + lastStr;
        } else {
            return "";
        }
    }

    /**
     * 去除字符串数组中的重复值
     * @param stringArray 字符串数组
     * @return
     * */
    public static String[] filterRepeat(String[] stringArray) {
        ArrayList arrayList = new ArrayList();
        String[] var2 = stringArray;
        int var3 = stringArray.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String str = var2[var4];
            if(!arrayList.contains(str)) {
                arrayList.add(str);
            }
        }

        return (String[])((String[])arrayList.toArray(new String[0]));
    }

    
    /**
     * 获取字符串的中文个数
     * @param str
     * */
    public static int getChineseCount(String str) {
        return str.getBytes().length - str.length();
    }


    /**
     * 判断请求IP是否包含在ip数组中
     * @param requestIP ip地址
     * @param ips 存放ip的String数组
     * */
    public static boolean checkIP(String requestIP, String[] ips) {
        String[] var2 = ips;
        int var3 = ips.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            String ip = var2[var4];
            if(requestIP.equals(ip)) {
                return true;
            }

            if(ip.indexOf("-") >= 0) {
                String[] ipPart = requestIP.split("\\.");
                String[] ipOpenPart = ip.split("\\-")[0].split("\\.");
                String[] ipEndPart = ip.split("\\-")[1].split("\\.");
                if(ipOpenPart.length == ipPart.length && ipEndPart.length == ipPart.length) {
                    boolean flag = true;

                    for(int i = 0; i < ipPart.length; ++i) {
                        if(ipPart[i].compareTo(ipOpenPart[i]) < 0 || ipPart[i].compareTo(ipEndPart[i]) > 0) {
                            flag = false;
                        }
                    }

                    if(flag) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    
    /**
     * 效验字符串是否符合正则表达式格式
     * @param value 被校验的字符串
     * @param regexp 正则表达式
     * */
    public static boolean checkRegexp(String value, String regexp) {
        return Pattern.compile(regexp).matcher(value).matches();
    }

    
    /**
     * 获取文件名称
     * @param 文件路径
     * @return
     * */
    public static String getBaseName(String path) {
        int pos = path.lastIndexOf("\\");
        if(!System.getProperty("os.name").contains("Win")) {
            pos = path.lastIndexOf("/");
        }

        return path.substring(pos + 1);
    }

    /**
     * 对单引号、百分号、左中括号、右中括号等执行替换处理
     * @param s
     * */
    public static String doLikeEscape(String s) {
        if(checkStr(s)) {
            StringBuffer result = new StringBuffer();

            for(int i = 0; i < s.length(); ++i) {
                char ch = s.charAt(i);
                if(ch == 39) {
                    result.append("''");
                } else if(ch == 37) {
                    result.append("[%]");
                } else if(ch == 91) {
                    result.append("[[]");
                } else if(ch == 93) {
                    result.append("[]]");
                } else {
                    result.append(ch);
                }
            }

            return result.toString();
        } else {
            return s;
        }
    }

    private static String getIPOnLinux() throws Exception {
        String ip = "";

        try {
            Enumeration e1 = NetworkInterface.getNetworkInterfaces();

            while(e1.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface)e1.nextElement();
                if(ni.getName().equals("eth0")) {
                    Enumeration e2 = ni.getInetAddresses();

                    while(e2.hasMoreElements()) {
                        InetAddress ia = (InetAddress)e2.nextElement();
                        if(!(ia instanceof Inet6Address)) {
                            ip = ia.getHostAddress();
                        }
                    }

                    return ip;
                }
            }
        } catch (Exception var5) {
            ;
        }

        return ip;
    }

    
    /**
     * 判断字符串不为空
     * @param str
     * */
    public static BigDecimal toBigDecimal(String str) {
        BigDecimal result = new BigDecimal(0);
        if(checkObj(str) && !str.equals("null")) {
            result = new BigDecimal(str);
        }

        return result;
    }

    /**
     * Oracle CLOB类型转换成String
     * @param clob
     * */
    public static String ClobToString(Clob clob) throws SQLException, IOException {
        String reString = "";
        Reader is = clob.getCharacterStream();
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();

        StringBuffer sb;
        for(sb = new StringBuffer(); s != null; s = br.readLine()) {
            sb.append(s);
        }

        reString = sb.toString();
        return reString;
    }
    
    /**
	  * 验证手机号码
	  * @param mobiles
	  * @return
	  */
    public static boolean checkMobileNumber(String mobileNumber){
		boolean flag = false;
		try{
			Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
			Matcher matcher = regex.matcher(mobileNumber);
			flag = matcher.matches();
		}catch(Exception e){
			flag = false;
		}
		return flag;
	 }
    
	 /**
	  * 验证邮箱
	  * @param email
	  * @return
	  */
	public static boolean checkEmail(String email){
		boolean flag = false;
		try{
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		}catch(Exception e){
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 写txt里的单行内容
	 * @param filePath  文件路径
	 * @param content  写入的内容
	 */
	public static void writeFile(String fileP,String content){
		String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
		filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
		if(filePath.indexOf(":") != 1){
			filePath = File.separator + filePath;
		}
		try {
	        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");      
	        BufferedWriter writer=new BufferedWriter(write);          
	        writer.write(content);      
	        writer.close(); 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 字符串转换为字符串数组
	 * @param str 字符串
	 * @param splitRegex 分隔符
	 * @return
	 */
	public static String[] str2StrArray(String str,String splitRegex){
		if(isEmpty(str)){
			return null;
		}
		return str.split(splitRegex);
	}
	
	/**
	 * 用默认的分隔符(,)将字符串转换为字符串数组
	 * @param str	字符串
	 * @return
	 */
	public static String[] str2StrArray(String str){
		return str2StrArray(str,",\\s*");
	}
	
	/**
	 * 随机生成六位数验证码 
	 * @return
	 */
	public static int getRandomNum(){
		 Random r = new Random();
		 return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
	}
	
	/**
	 * 读取txt里的单行内容
	 * @param filePath  文件路径
	 */
	public static String readTxtFile(String fileP) {
		try {
			
			String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";	//项目路径
			filePath = filePath.replaceAll("file:/", "");
			filePath = filePath.replaceAll("%20", " ");
			filePath = filePath.trim() + fileP.trim();
			if(filePath.indexOf(":") != 1){
				filePath = File.separator + filePath;
			}
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { 		// 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
				new FileInputStream(file), encoding);	// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					return lineTxt;
				}
				read.close();
			}else{
				System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
		}
		return "";
	}
    
	/**
	 * 检测字符串是否不为空(null,"","null")
	 * @param s
	 * @return 不为空则返回true，否则返回false
	 */
	public static boolean notEmpty(String s){
		return s!=null && !"".equals(s) && !"null".equals(s);
	}
	
	/**
	 * 检测字符串是否为空(null,"","null")
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(String s){
		return s==null || "".equals(s) || "null".equals(s);
	}
	
}
